package com.guli.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {

    //单点服务端登录地址
    @Value("${sso.server.url}")
    private String ssoServerUrl;
    @Value("${sso.redirect.url}")
    private String redirect_url;

    /**
     * 无需登录就可以访问
     * @return
     */
    @GetMapping("/hello")
    @ResponseBody
    public String hello(){

        return "hello";
    }


    /**
     * 登录才能访问
     * @param token 只要去登录成功才会带回token
     * @return
     */
    @GetMapping("/employees")
    public String employees(@RequestParam(value = "token",required = false) String token, Model model, HttpSession session){
        if(!StringUtils.isEmpty(token)){
            //只要去登录成功才会带回token
            //去单点服务获取登录用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser",body);
        }
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser == null){
            //没登录，跳转到登录服务器进行登录
            return "redirect:" + ssoServerUrl + "?redirect_url=" + redirect_url;
        }else{
            List<String> emps = new ArrayList<String>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps",emps);
            return "list";
        }
    }

}
